package cn.itsource._01simple;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;
import java.io.IOException;

/**
 * 作者： CTL
 * 描述： 消费者
 * 创建时间： 2023-06-13 14:16
 */

public class ConsumerTest {
    public static void main(String[] args) throws Exception {
        // 1.创建连接工厂
        ConnectionFactory factory = new ConnectionFactory();
        // 2.设置连接地址
        factory.setHost("127.0.0.1");
        // 3.创建一个连接对象
        Connection connection = factory.newConnection();
        // 4.从连接对象中创建一个通道
        Channel channel = connection.createChannel();
        // 5.监听某一个队列并从该队列中获取消息
        /**
         * channel.basicConsume：队列名
         * new DefaultConsumer(channel)：监听类
         */
        // 当只有两个参数是，表示，会接收队列的历史消息
        //channel.basicConsume(ProducerTest.AIMPLE_QUEUE_NAME,new DefaultConsumer(channel){

        // 第二个参:true:表示不会去接收历史消息
        channel.basicConsume(ProducerTest.AIMPLE_QUEUE_NAME,false,new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println(" [x] Received '" + message + "'");
                System.out.println(envelope.getDeliveryTag());
                channel.basicAck(envelope.getDeliveryTag(),false);
            }
        });
    }
}
